import java.util.Stack;

class Solution946 {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        if(popped.length != pushed.length) return false ;
        Stack<Integer> stack = new Stack<>();
        int i= 0  , j  = 0 , len = pushed.length ;
        while(j < len && i < len ){
             stack.push(pushed[i++]) ; 
                while((!stack.empty()) && stack.peek() == popped[j]){
                    j ++ ;
                    stack.pop() ;
                }
        }
        while((!stack.empty()) && j < len){
            if(stack.pop() == popped[j]){
                j ++ ;
            }else{
                return false ;
            }
        }
        return true ;
    }
}